using Framework.Interface;
using UnityEngine;
using UnityEngine.UI;

namespace Game.Logic.App.Hotfix
{
    public class HotfixView : MonoBehaviour
    {
        public GameObject objHotfix;
        public Text txtProcess;
        public Text txtMsg;
        public Slider sldProcess;

        public Button btnConfirm;

        private void Start()
        {
            btnConfirm.onClick.AddListener(() =>
            {
                EventsManager.Instance.Broadcast(new EnterGame{});
            });
        }

        private void OnEnable()
        {
            EventsManager.Instance.Add<HotfixMsgEvent>(UpdateMsg);
            EventsManager.Instance.Add<HotfixProcessEvent>(UpdateMsg);
            EventsManager.Instance.Add<HotfixConfirmEvent>(UpdateMsg);
            ResetUI();
        }

        private void OnDisable()
        {
            ResetUI();
            EventsManager.Instance.Remove<HotfixMsgEvent>(UpdateMsg);
            EventsManager.Instance.Remove<HotfixProcessEvent>(UpdateMsg);
            EventsManager.Instance.Remove<HotfixConfirmEvent>(UpdateMsg);
        }

        private void UpdateMsg(IListener listener)
        {
            if (listener is HotfixMsgEvent)
            {
                SetHotfix(true);
                txtMsg.text = (listener as HotfixMsgEvent).msg;
            }
            else if (listener is HotfixProcessEvent)
            {
                SetHotfix(true);
                float process = (listener as HotfixProcessEvent).process;
                txtProcess.text = $"{process.ToString("0.00")}%";
            }
            else if (listener is HotfixConfirmEvent)
            {
                SetHotfix(false);
                SetConfirm(true);
            }
        }

        private void SetHotfix(bool showHotfix)
        {
            if (objHotfix.activeSelf != showHotfix)
                objHotfix.SetActive(showHotfix);
        }

        private void SetConfirm(bool showConfirm)
        {
            if (btnConfirm.gameObject.activeSelf != showConfirm)
                btnConfirm.gameObject.SetActive(showConfirm);
        }

        private void ResetUI()
        {
            txtMsg.text = "";
            txtProcess.text = "0%";
            sldProcess.value = 0;
            SetHotfix(false);
            SetConfirm(false);
        }
    }
}
